package ch.zbw.pra.sysventory.business.businessObject.scan;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.pra.sysventory.model.Software;

/**
 * Gibt alle Installierten Software mittels WMI Schnittstelle auf einem bestimmten Host zurück
 * 
 * @author Ralph Koster
 */

public class ScanSoftwareBusinessObject implements Serializable {

	private static final long serialVersionUID = -5360935155011098913L;
	private static Logger LOG = LoggerFactory.getLogger(ScanSoftwareBusinessObject.class);
	
	private List<Software> softwares;


	public ScanSoftwareBusinessObject() {
		this.softwares = new ArrayList<Software>();
	}

	public List<Software> getAllSoftwareFromHost(String host) {
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM win32_Product";
		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;

			while (enumVariant.hasMoreElements()) {

				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a java form.
				String softwareName = Dispatch.call(item, "Caption").toString();
				String softwareVersion = Dispatch.call(item, "Version").toString();
				String softwareVendor = Dispatch.call(item, "Vendor").toString();
				
				LOG.debug("Software found: " + softwareName + " " + softwareVersion
						+ " " + softwareVendor);

				Software software = new Software(softwareName, softwareVersion, softwareVendor);
				softwares.add(software);

			}
		} catch (Exception e) {
			LOG.debug("Failed to load softwares from host: " + host);
			LOG.error(e.toString());
		}
		return softwares;
	}
}
